<?php

namespace app\store\controller\setting;

use app\store\controller\Controller;

/**
 * 汽车型号管理
 * Class User
 * @package app\store\controller
 */
class Autotype extends Controller
{
    public function index() {
        $where = [];
        $brand_id = $this->request->param('auto_brand_id');
        if( $brand_id > 0) {
            $where['auto_brand_id'] = $brand_id;
        }
        $list = db("auto_type")->order(['sort' => 'DESC' , 'id' => 'DESC'])->where($where)->paginate(15, false, ['query' => $this->request->request()])->each(function($item, $key){
            $item['brand_name'] = db("auto_brand")->where(['id' => $item['auto_brand_id']])->value("title");
            return $item;
        });
        return $this->fetch('', compact('list'));
    }
    
    public function add() {
        return $this->post();
    }
    
    public function edit(){
        $id = $this->request->param('id/d' , 0);
        if( $id <= 0 ) $this->error('数据格式错误');
        $data = db("auto_type")->where(['id' => $id])->find();
        if( !$data ) $this->error('数据不存在，请核对');
        return $this->post( $data );
    }
    
    private function post( $save_data = '' ) {
        if( $this->request->isAjax() ) {
            $params = $this->postData('type');
            $id = $this->request->post('id/d' , 0);
            $url = url("setting.autotype/index" , array('auto_brand_id' => $params['auto_brand_id']) , false , true);
            if( $id <= 0 ) {
                $params['create_time'] = time();
                $res = db("auto_type")->insert($params);
                if( $res ) {
                    $this->success('型号新增成功' , $url);
                } else {
                    $this->error('添加失败，请重试');
                }
            } else {
                $res = db("auto_type")->where(['id' => $id])->update($params);
                if( $res ) {
                    $this->success('型号修改成功' , $url);
                } else {
                    $this->error('修改失败，请重试');
                }
            }
        }
        $brand_list = db("auto_brand")->where(['status' => 1])->select();
        return $this->fetch('', compact('save_data' , 'brand_list'));
    }
    
    public function delete() {
        $id = $this->request->post('id/d' , 0);
        if( $id <= 0 ) $this->error('参数错误，请核对');
        $res = db('auto_type')->where(['id' => $id])->delete();
        if( $res ) {
            $this->success('删除成功');
        } else {
            $this->error("操作失败");
        }
    }
}